package com.ourteam.frame.web;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.tools.generic.SafeConfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class PropUtils extends SafeConfig {

	public Object value(Object obj, String propertyName) throws Exception {
		if (obj == null) {
			return null;
		} else {
			return PropertyUtils.getProperty(obj, propertyName);
		}

	}

	public int size(Object obj) throws Exception {
		if (obj != null && obj.getClass().isArray()) {
			return ((Object[]) obj).length;
		} else if (obj instanceof Collection<?>) {
			return ((Collection<?>) obj).size();
		} else {
			return 0;
		}
	}

	public boolean isEmpty(Object obj) throws Exception {
		if (obj != null && obj.getClass().isArray()) {
			return ArrayUtils.isEmpty(((Object[]) obj));
		} else if (obj instanceof Collection<?>) {
			return CollectionUtils.isEmpty(((Collection<?>) obj));
		} else if (obj instanceof String) {
			return StringUtils.isEmpty((String) obj);
		} else {
			return obj == null;
		}
	}

	public Map<Object, Object> toMap(String mapScript) throws Exception {
		
		if(StringUtils.isEmpty(mapScript)) {
			return MapUtils.EMPTY_MAP;
		}

		JSONObject jsonObject = JSON.parseObject(mapScript);

		Map<Object, Object> map = new HashMap<>();

		for (Iterator<String> iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
			String key = iterator.next();
			map.put(key, jsonObject.get(key));
		}

		return map;

	}
}
